package sushil.luc.gui;

import android.app.ActionBar;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ugrokit.api.Ugi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sushil.luc.item.Item;
import sushil.luc.item.ItemStatus;
import sushil.luc.msc.DateUtil;
import sushil.luc.msc.MyItemListAdapter;
import sushil.luc.msc.UgroKitActivity;
import sushil.luc.ticket.Ticket;
import sushil.luc.ticket.TicketManagerTrucker;
import sushil.luc.ticket.TicketService;
import sushil.luc.truckersmartrfid.R;

public class ScanTicketActivity extends UgroKitActivity {

	private int positioninListview;

	private  static Ticket currentTicket;
	private  static ListView ItemList;
	private  static Button btnNavigation;
	private TextView ticketInfo;
	private TextView clientName;
	private TextView clientAdress;
	private ActionBar actionbar;
	private static Context context;
	private TicketManagerTrucker trucker;
	
	private static final String KEY_LABEL ="Big Text";
	private static final String KEY_HELP ="Help Text";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scanticket);
		
		// get the position of the Ticket which was selected
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			positioninListview = extras.getInt("Position_InList", -1);
		}
		
		if (positioninListview == -1)
		{
			// if we could not find the selected Ticket, go back to the previous view
			finish();
		}
		else {
			// init all the graphical objects
			ItemList = (ListView)findViewById(R.id.itemlist);

			
			btnNavigation = (Button) findViewById(R.id.navigation); 
			btnNavigation.setText("Set Client Address as destination");
			
			ticketInfo = (TextView) findViewById(R.id.ticketinfo);
			clientName = (TextView) findViewById(R.id.clientname);
			clientAdress = (TextView) findViewById(R.id.clientadress);
			
			context =this;
			
			trucker = new TicketManagerTrucker(context);
			
			// get the selected Ticket
			currentTicket = TicketManagerTrucker.ticketlist.get(positioninListview);
			
			// Saves the information from the Ticket to the Texviews
			initTicketInfo();
			
			//Inits the Items into the list
			fillItemList();
			
			btnNavigation.setOnClickListener(new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// set the client address and tell the user
						TruckerMapFragment.customerAdress=currentTicket.getTicketCustomer().getAddress();
						(Toast.makeText(context, "Client Adress set!", Toast.LENGTH_SHORT)).show();
				}
			});
			
			// init the action bar and assign the current status
			 actionbar = getActionBar();
			 actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
			 actionbar.setSubtitle(currentStatus);
		}
	}
	/**
	 * Inits the Textviews with the appropriate text
	 */
	private void initTicketInfo()
	{
		String info;
		info = "TicketId: "+currentTicket.getTicketID();
		info = info+ " | Delivery Date: "+DateUtil.formatDate(currentTicket.getDeliveryDate());
		
		ticketInfo.setText(info);	

		String clientname = "Client Name: "+currentTicket.getTicketCustomer().getName();
		clientName.setText(clientname);
		
		String clientadress = "Client Address: "+currentTicket.getTicketCustomer().getAddress();
		clientAdress.setText(clientadress);
	}
	
	/**
	 * Fills the Items into the Listview
	 */
	public static void fillItemList()
	{
		ItemList.setAdapter(null);
    	
		List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
		
    	Map<String, String> group;
    	
    	// get the items from the ticket
    	List<Item> allItems = currentTicket.getItems();
    	
    	for (int i =0; i<allItems.size();i++)
    	{
    		Item tmp = allItems.get(i);
    		
    		group = new HashMap<String, String>();
        	
    		// get the important data
        	group.put( KEY_LABEL,  tmp.getItemID() );
        	group.put( KEY_HELP, "Desc: "+tmp.getItemName() );

        	groupData.add(group);
    	}
    	
    	// create an adapter which colors the items in respect to their status
    	MyItemListAdapter adapter = new MyItemListAdapter( context, groupData, android.R.layout.simple_list_item_2,
    	                                                   new String[] { KEY_LABEL, KEY_HELP },
    	                                                   new int[]{ android.R.id.text1, android.R.id.text2 } , allItems);
    	ItemList.setAdapter(adapter);
    	
    	// if all the items where found by the trucker, enable the button. 
    	if (checkTicketStatus())
    	{
    		btnNavigation.setEnabled(true);
    	}
    	else
    	{
    		btnNavigation.setEnabled(false);
    	}
	}

	public void onDestroy()
	{
		boolean res = checkTicketStatus();
		if (res)
		{
			TicketService ts = new TicketService();
			ts.updateTicketStaged(currentTicket);
		}
		
		super.StopInventory();
		super.mHandler.modeTruckerCheck(false, null);
		
		super.onDestroy();
	}
	
	
	/**
	 * Checks if all the Items where found by the trucker ( e.g. ItemStatus of all items == Staged)
	 * @return true if all items were found. False if one or more items where not yet found.
	 */
	private static boolean checkTicketStatus()
	{
		boolean res = true;
		
		List<Item> items = currentTicket.getItems();
		
		// check if all the items have the status Staged
		for (Item i :items)
		{
			if (i.getStatus().equals(ItemStatus.Staged))
				res = res && true;
			else
				res = res && false;
		}
		
		// if the ticket does not contain any item. => no delivery needed
		if (items.size()==0)
			res = false;
		
		// update the database entry of this ticket
	/*	if (res)
		{
			TicketService ts = new TicketService();
			ts.updateTicketStaged(currentTicket);
		}*/
		
		return res;
	}
	
	   public void onResume()
	   {
		   super.onResume();
		   
		   //start the Rfid scan and set the correct Handler modes
		   super.StartInventory();
		   Log.d("ScanTicketActivity", "onResume");
		   super.mHandler.modeTruckerCheck(true, currentTicket);
	   }
	   
	   public void onPause()
	   {
		   super.onPause();
		 //stop the Rfid scan and disable the correct Handler mode
		   super.StopInventory();
		   Log.d("ScanTicketActivity", "onPause");
		   super.mHandler.modeTruckerCheck(false, null);
	   }
	   
		@Override
		/**
		 * If the connection from the ugrokit changes, this methode gives feedback to the user
		 */
		public void connectionStateChanged(Ugi.ConnectionStates connectionState) {
			super.connectionStateChanged(connectionState);
			// update the Status
			super.calculateStatus();
			notifiySatusUpdate();
		}
		
		/**
		 * Update the status bar
		 */
		public void notifiySatusUpdate()
		{
			if (actionbar!=null)
				actionbar.setSubtitle(currentStatus);
		}
	   
}
